package cn.dida.controller;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.dida.model.OptLog;
import cn.dida.model.Pageable;
import cn.dida.model.UserSession;
import cn.dida.service.OptLogService;

/**
 * 操作日志
 * @author weiwei
 *
 */
@Controller
public class OptLogController extends BaseController {
    @Autowired
    private OptLogService optLogService;
    /**
	 * 操作日志列表
	 * @param companyId 公司id
	 * @param keyword 查询条件
	 * @param timeLimitStart 操作时间(开始)
	 * @param timeLimitEnd 操作时间(结束)
	 * @param page 分页游标
	 * @return ModelAndView 操作日志列表页面
	 */
    @GetMapping("/optlog")
    public ModelAndView queryLog(HttpServletRequest request, String keyword, Long timeLimitStart, Long timeLimitEnd, Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);

        page = (page == null || page < 1) ? 1 : page;
        keyword = StringUtils.trimToNull(keyword);

        if (timeLimitStart == null || timeLimitEnd == null) {
            Calendar now = Calendar.getInstance();
            Calendar sevenDaysAgo = Calendar.getInstance();
            sevenDaysAgo.clear();
            sevenDaysAgo.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE));
            sevenDaysAgo.add(Calendar.DATE, -7);

            Calendar today = Calendar.getInstance();
            today.clear();
            today.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE), 23, 59, 59);
            today.set(Calendar.MILLISECOND, 999);

            timeLimitStart = sevenDaysAgo.getTimeInMillis();
            timeLimitEnd = today.getTimeInMillis();
        }

        Pageable<OptLog> optlogHistory = optLogService.queryLog(userSession.getCompanyId(), keyword, timeLimitStart, timeLimitEnd, page);

        model.put("optlogHistory", optlogHistory);
        model.put("keyword", keyword);
        model.put("timeLimitStart", timeLimitStart);
        model.put("timeLimitEnd", timeLimitEnd);
        return new ModelAndView("optlog").addAllObjects(model);
    }

}
